package com.myex.demo.service;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.myex.demo.common.util.JsonUtil;
import com.myex.demo.common.util.RedisUtil;
import com.myex.demo.dao.MiaoShaDao;
import com.myex.demo.model.Goods;
import com.myex.demo.model.OrderMsg;
import com.myex.demo.model.OrderRecord;
import com.sun.org.apache.xpath.internal.operations.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.security.auth.callback.Callback;
import java.beans.Transient;
import java.util.List;
import java.util.Map;
import java.util.UUID;


@Service
public class MiaoShaService {

    @Autowired
    MiaoShaDao miaoShaDao;

    public List<Goods> selectAllGoods() {
        return miaoShaDao.findAllGoods();
    }

    public Goods findGoods(String goodsId) {

        return miaoShaDao.findGoodsById(goodsId);
    }

    //通过商品ID查询库存数量
    public int queryGoodsStockById(String goodsId){
        return miaoShaDao.findGoodsStockById(goodsId);
    }


    //根据用户ID和商品ID查询是否下过单
    public List<OrderRecord> queryOrderByUserIdAndCoodsId(String userId,String goodsId){
        return miaoShaDao.findOrderByUserIdAndGoodsId(userId,goodsId);
    }


    //减少库存,下订单,是一个事务
    @Transactional
    public void miaosha(OrderMsg orderMsg) {

        //1 减少数据库库存
        int count = miaoShaDao.updateGoodsStock(orderMsg.getGoodsId(),orderMsg.getNum());
        if(count > 0){
            try {
                // 减少库存成功后下订单
                orderMsg.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                miaoShaDao.insertOrder(orderMsg);
                //将生成的订单放入缓存
                RedisUtil.set("order"+orderMsg.getUserId()+"_"+orderMsg.getGoodsId(), JSONUtil.toJsonPrettyStr(orderMsg));
            } catch (Exception e) {
                //出现异常手动回滚
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                RedisUtil.incr(orderMsg.getGoodsId(),Long.parseLong(orderMsg.getNum()));
            }
        }else {
            //减少库存失败做一个标记,代表商品已经卖完了
            RedisUtil.set("goodsover"+orderMsg.getGoodsId(), true);
        }

    }


    public OrderMsg getMiaoShaResult(String userId, String goodsId) {
        String orderJson = (String) RedisUtil.get("order"+userId+"_"+goodsId);
        OrderMsg data = JsonUtil.string2Obj(orderJson,OrderMsg.class);
        return data;
    }

    //查询是否卖完了
    public boolean getGoodsOver(String goodsId) {
        return RedisUtil.hasKey("goodsover"+goodsId);
    }



}
